package com.erpanderp.wam.adm.model.service;

import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.Session;

import com.erpanderp.wam.adm.model.entity.Module;
import com.erpanderp.wam.adm.model.entity.Permission;
import com.erpanderp.wam.util.HibernateUtil;

public class PermissionDAO {

	public List<Permission> getAllPermissions()
	{
		List<Permission> permissions = null;
		
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			String queryString = "from Permission m";
			Query query = session.createQuery(queryString);
			query.setCacheable(false);
			permissions = (List<Permission>) query.list();	
			session.close();
			return permissions;
			
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	public Permission createPermission(Permission permission){
		try{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
		System.out.println("FLUSH MODE: " + session.getFlushMode());
		session.setFlushMode(FlushMode.COMMIT);
		session.save(permission);
		session.getTransaction().commit();
		
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		
		return permission;
		
	}
	
	public boolean isPermissionAvailable(String permission)
	{
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			String queryString = "from Permission p where p.permission = :permission";
			Query query = session.createQuery(queryString);
			query.setCacheable(false).setString("permission", permission);
			List permissions = (List<Permission>) query.list();
			
			session.close();
			
			if(permissions != null && permissions.size() > 0){
				return false;
			}else{
				return true;
			}		
		}catch(Exception e){
			e.printStackTrace();
			return true;
		}
	}
	
	public boolean isPermissionDisplayNameAvailable(String displayName)
	{
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			String queryString = "from Permission p where p.displayName = :displayName";
			Query query = session.createQuery(queryString);
			query.setCacheable(false).setParameter("displayName", displayName);
			List permissions = (List<Permission>) query.list();
			
			session.close();
			
			if(permissions != null && permissions.size() > 0){
				return false;
			}else{
				return true;
			}		
		}catch(Exception e){
			e.printStackTrace();
			return true;
		}
	}

	
	public static void main(String a[]){
		System.out.println(new PermissionDAO().isPermissionDisplayNameAvailable("Edit Employee Info"));
	}
}
